//
//  FlightListController.m
//  lv678
//
//  Created by apple on 15/8/12.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//  飞机航班列表界面

#import "FlightListController.h"
#import "FlightListModel.h"
#import "FlightHeaderView.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "CommonLoading.h"
#import "CabinsCell.h"
#import "FlightCodeListModel.h"
#import "PlaneOrderController.h"

@interface FlightListController ()<FlightHeaderViewDelegate,CabinsCellDelegate>
@property (nonatomic, strong)UIView *refreshView;//刷新控件xib属性
@property (nonatomic, strong)NSMutableArray *group;

@end

@implementation FlightListController
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self initTableView];
    
}

#pragma mark - ***************设置样式，获取数据***************
- (void)initTableView{
    
    self.navigationItem.title = @"航班";
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    
    self.tableView.separatorStyle = NO;
    
    //加载刷新控件
    UIView *view = [[CommonLoading initCommonLoading]refreshLoading];
    self.refreshView = view;
    [self.tableView addSubview:view];
    
    [self loadData];
    
    //设置tableview的footer和header的高度
    self.tableView.sectionFooterHeight = 1;
    self.tableView.sectionHeaderHeight = 60;
}


#pragma mark - ***************下拉刷新***************
- (void)loadMoreData{
    [self.tableView.footer beginRefreshing];
    [self loadMoreData];
}

#pragma mark - ***************请求接口加载数据***************
- (void)loadData{
    self.group = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle]pathForResource:@"UrlList.plist" ofType:nil];
    NSDictionary *tempDic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSString *url = [tempDic objectForKey:@"plane"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer  = [AFJSONRequestSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    NSDictionary *date =self.flightData;
        [manager POST:url parameters:date success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSArray *dateLis = [responseObject valueForKey:@"Flight"];
            for (NSDictionary *dict in dateLis) {
                FlightListModel *model = [FlightListModel flightWithDict:dict];
                [self.group addObject:model];
            }
            self.tableView.separatorStyle = YES;
            [self.refreshView removeFromSuperview];
            [self.tableView reloadData];
            [self popPreviousView];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [self.refreshView removeFromSuperview];
            self.tableView.separatorStyle = NO;
            //网络提示，后期需改动
            UIAlertView *alert   = [[UIAlertView alloc]initWithTitle:@"错误" message:@"网络连接失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }];
}

#pragma mark - ***************Table数据源***************

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.group.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    FlightListModel *model = self.group[section];
    if (model.Visible) {
        return model.Cabins.count;
    }else{
        return 0;
    }

}

#pragma mark - ***************单元格***************
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    

    
    FlightListModel *model = self.group[indexPath.section];
    FlightCodeListModel *code_model = model.Cabins[indexPath.row];
    CabinsCell *cell = [CabinsCell cabinsWithTableView:tableView];
    cell.delegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor colorWithRed:245.0f/255 green:245.0f/255 blue:245.0f/255 alpha:1];
    cell.list_model = model;
    [cell setList:model setCode:code_model];
    return cell;
}

#pragma mark - **************点击cell**************
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - ***************设置TableView的header视图***************
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
        [self setHeaderViewForTableView];
    
    FlightListModel *model = self.group[section];
    FlightHeaderView *headerVw = [FlightHeaderView headerViewForFlight:tableView];
    headerVw.delegate = self;
    headerVw.flightModels = model;
    headerVw.tag = section;
    return headerVw;
}
#pragma mark - ***************设置TableView的footer视图背景色***************
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 1)];
    footView.backgroundColor = [UIColor colorWithRed:235.0f/255 green:235.0f/255 blue:241.0f/255 alpha:1];
    return footView;
}

#pragma mark - ***************如果没有航班则进行提示***************
- (void)popPreviousView{
    if (self.group.count == 0) {
        UIView *alertView = [[CommonLoading initCommonLoading]noDataTips];
        [self.tableView addSubview:alertView];
        self.tableView.separatorStyle = NO;
    }
}

#pragma mark - **************设置顶部视图**************
- (void)setHeaderViewForTableView{
    
    //当前时间
    NSDate *current_Day = [NSDate date];
    //前一天时间
//    NSDate *last_Day = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:current_Day];
    
    //后一天时间
//    NSDate *next_Day = [NSDate dateWithTimeInterval:24*60*60 sinceDate:current_Day];

     CGFloat appW = self.view.frame.size.width;
    
    UIView *headerView = [[UIView alloc]init];
    headerView.frame = CGRectMake(0, 0, appW, 50);
    headerView.backgroundColor = [UIColor colorWithRed:248.0f/255 green:248.0f/255 blue:248.0f/255 alpha:1];
    
    CGFloat appH = headerView.frame.size.height;
   
    
//    UIButton *to_Top = [[UIButton alloc]init];
//    to_Top.frame = CGRectMake(appW-30, appH-30, 30, 30);
//    to_Top.backgroundColor = [UIColor redColor];
//    [to_Top setTitle:@"Top" forState:UIControlStateNormal];
//    to_Top.tag = 200;
//    [self.tableView addSubview:to_Top];
    
    
    
    //前一天按钮
    UIButton *btn_left = [[UIButton alloc]init];
    btn_left.frame = CGRectMake(0, appH/4, appW/6, appH/2);
    [btn_left setImage:[UIImage imageNamed:@"fa-angle-down"] forState:UIControlStateNormal];
    
    UILabel *lbl_last = [[UILabel alloc]init];
    lbl_last.frame = CGRectMake(appW/6, appH/4, appW/6, appH/2);
//    lbl_last.text = @"前一天";
    lbl_last.font = [UIFont systemFontOfSize:14.0];
    
    

    
    //时间label
    UILabel *lbl_Time = [[UILabel alloc]init];
    lbl_Time.frame = CGRectMake(appW/4, appH/4, appW/2, appH/2);
    lbl_Time.textColor = [UIColor blueColor];
    NSString *flight_count = @"  共有";
    flight_count = [[flight_count stringByAppendingString:[NSString stringWithFormat:@"%lu",(unsigned long)self.group.count]]stringByAppendingString:@"班"];
    NSString *currentTime = [[self getNsDate:current_Day]stringByAppendingString:flight_count];
    lbl_Time.font = [UIFont systemFontOfSize:14.0];
    lbl_Time.text = currentTime;
    
    
    UIButton *btn_right = [[UIButton alloc]init];
    btn_right.frame = CGRectMake(appW/6*5, appH/4, appW/6, appH/2);
    [btn_right setTitle:@"后一天" forState:UIControlStateNormal];
    
    [headerView addSubview:btn_left];
    [headerView addSubview:lbl_last];
    [headerView addSubview:btn_right];
    [headerView addSubview:lbl_Time];
    
    self.tableView.tableHeaderView = headerView;
}

#pragma mark - ***************实现header视图的代理***************
- (void)flightBtnDidClick:(FlightHeaderView *)flightHeaderView{

    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:flightHeaderView.tag];

    //单独刷新所点击的组
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - **************获取当前系统时间**************
- (NSString *)getNsDate:(NSDate *)data{
//    NSDate *  senddate=[NSDate date];

    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];

    [dateformatter setDateFormat:@"YYYY-MM-dd"];

    NSString *  locationString=[dateformatter stringFromDate:data];

    return locationString;
}

- (void)pushViewToOrder:(FlightListModel *)listModel sendData:(FlightCodeListModel *)codeModel{

    NSDictionary *plane_Detail = @{@"offCityName":self.offName,@"arrCityName":self.arrName};
    PlaneOrderController *order_View = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:@"PlaneOrderController"];
    order_View.flightDetail = plane_Detail;
    order_View.listModel = listModel;
    order_View.codeModel = codeModel;
    [self.navigationController pushViewController:order_View animated:YES];
}
@end
